#!/usr/bin/env perl

# Copyright (C) 2006-2009 Martin A. Hansen.

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

# http://www.gnu.org/copyleft/gpl.html

# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

use strict;
use warnings;

use lib $ENV{ 'BP_PERL' };

use CGI;
use URI::Escape;
use Data::Dumper;
use Digest::MD5;
use Time::HiRes;
use Maasha::Common;
use Maasha::Filesys;
use Maasha::Calc;
use Maasha::XHTML;
use Maasha::BGB::Session;
use Maasha::BGB::Track;
use Maasha::BGB::Draw;

my ( $cgi, $cookie, @html );

$cgi    = new CGI;
$cookie = cookie_default( $cgi );;

push @html, Maasha::XHTML::html_header(
    cgi_header  => 1,
    title       => 'Biopieces Genome Browser',
    css_file    => 'bgb.css',
    author      => 'Martin A. Hansen, mail@maasha.dk',
    description => 'Biopieces Genome Browser',
    keywords    => [ qw( Biopieces biopiece genome browser viewer bacterium bacteria prokaryote prokaryotes ) ],
    no_cache    => 1,
);

push @html, Maasha::XHTML::h1( txt => "Biopieces Genome Browser", class => 'center' );
push @html, Maasha::XHTML::form_beg( action => $cookie->{ 'SCRIPT' }, method => "post", enctype => "multipart/form-data" );

push @html, page( $cookie );

push @html, Maasha::XHTML::form_end;
push @html, Maasha::XHTML::body_end;
push @html, Maasha::XHTML::html_end;

# push @html, Maasha::XHTML::hdump( { $cgi->Vars } );  # DEBUG
# push @html, Maasha::XHTML::hdump( $cookie );         # DEBUG
# push @html, Maasha::XHTML::hdump( \%ENV );           # DEBUG

print "$_\n" foreach @html;

# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SUBROUTINES <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> COOKIE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


sub cookie_default
{
    # Martin A. Hansen, November 2009.

    # Set a cookie with values from the CGI object or defaults.

    my ( $cgi,   # CGI object
       ) = @_;

    # Returns a hash.

    my ( $cookie, $session );

    $cookie = {};

    if ( $cgi->param( 'nav_search' ) )
    {
        if ( $cgi->param( 'nav_search' ) =~ /([0-9,]+)[ -]([0-9,]+)/ )
        {
            $cookie->{ 'NAV_START' } = $1;
            $cookie->{ 'NAV_END' }   = $2;
        }
        else
        {
            $cookie->{ 'SEARCH' } = $cgi->param( 'nav_search' );

            $cgi->param( 'page', 'search' );
        }
    }

    $cookie->{ 'SCRIPT' }      = Maasha::Common::get_scriptname();
    $cookie->{ 'DATA_DIR' }    = "Data";
    $cookie->{ 'SESSION_DIR' } = "Sessions";
    $cookie->{ 'LIST_PAGES' }  = [ qw( clade genome assembly contig browse ) ];
    $cookie->{ 'USER' }        = $cgi->param( 'user' );
    $cookie->{ 'PASSWORD' }    = $cgi->param( 'password' );
    $cookie->{ 'SESSION_ID' }  = $cgi->param( 'session_id' );

    $session = session_restore( $cookie );

    cookie_login( $cookie );

    # session_id_check( $cookie, $session );

    if ( $cookie->{ 'LOGIN_ERROR' } or $cookie->{ 'SESSION_ERROR' } )
    {
        $cookie->{ 'PAGE' } = 'login';
    }
    elsif ( $cookie->{ 'LOGIN' } )
    {
        if ( $cgi->param( 'genome' ) ) {
            $cookie->{ 'PAGE' } = 'browse';
        } else {
            $cookie->{ 'PAGE' } = $session->{ 'PAGE' } || 'clade';
        }
    }
    elsif ( not defined $cookie->{ 'USER' } )
    {
        $cookie->{ 'PAGE' } = 'login';
    }
    else
    {
         $cookie->{ 'PAGE' } = $cgi->param( 'page' ) || 'login';
    }

    $cookie->{ 'TRACK_STATUS' }    = $session->{ 'TRACK_STATUS' };
    $cookie->{ 'CLADE' }           = $cgi->param( 'clade' )       || $session->{ 'CLADE' };
    $cookie->{ 'GENOME' }          = $cgi->param( 'genome' )      || $session->{ 'GENOME' };
    $cookie->{ 'ASSEMBLY' }        = $cgi->param( 'assembly' )    || $session->{ 'ASSEMBLY' };
    $cookie->{ 'CONTIG' }          = $cgi->param( 'contig' )      || $session->{ 'CONTIG' };
    $cookie->{ 'Q_ID' }            = $cgi->param( 'q_id' )        || $session->{ 'Q_ID' };
    $cookie->{ 'NAV_START' }     ||= defined $cgi->param( 'nav_start' ) ? $cgi->param( 'nav_start' ) : $session->{ 'NAV_START' };
    $cookie->{ 'NAV_END' }       ||= defined $cgi->param( 'nav_end' )   ? $cgi->param( 'nav_end' )   : $session->{ 'NAV_END' };
    $cookie->{ 'NAV_CENTER' }      = $cgi->param( 'nav_center' );
    $cookie->{ 'S_BEG' }           = defined $cgi->param( 's_beg' ) ? $cgi->param( 's_beg' ) : $session->{ 'S_BEG' };
    $cookie->{ 'S_END' }           = defined $cgi->param( 's_end' ) ? $cgi->param( 's_end' ) : $session->{ 'S_END' };
    $cookie->{ 'STRAND' }          = $cgi->param( 'strand' )      || $session->{ 'STRAND' };
    $cookie->{ 'TRACK' }           = $cgi->param( 'track' );
    $cookie->{ 'ZOOM_IN1' }        = $cgi->param( 'zoom_in1' );
    $cookie->{ 'ZOOM_IN2' }        = $cgi->param( 'zoom_in2' );
    $cookie->{ 'ZOOM_IN3' }        = $cgi->param( 'zoom_in3' );
    $cookie->{ 'ZOOM_OUT1' }       = $cgi->param( 'zoom_out1' );
    $cookie->{ 'ZOOM_OUT2' }       = $cgi->param( 'zoom_out2' );
    $cookie->{ 'ZOOM_OUT3' }       = $cgi->param( 'zoom_out3' );
    $cookie->{ 'MOVE_LEFT1' }      = $cgi->param( 'move_left1' );
    $cookie->{ 'MOVE_LEFT2' }      = $cgi->param( 'move_left2' );
    $cookie->{ 'MOVE_LEFT3' }      = $cgi->param( 'move_left3' );
    $cookie->{ 'MOVE_RIGHT1' }     = $cgi->param( 'move_right1' );
    $cookie->{ 'MOVE_RIGHT2' }     = $cgi->param( 'move_right2' );
    $cookie->{ 'MOVE_RIGHT3' }     = $cgi->param( 'move_right3' );

    $cookie->{ 'IMG_WIDTH' }       = 1200;   # Width of browser image in pixels
    $cookie->{ 'IMG_HEIGHT' }      = 800;    # Height of browser image in pixels  # TODO: Redundant?
    $cookie->{ 'WIGGLE_HEIGHT' }   = 75;     # Height of Wiggle tracks in pixels
    $cookie->{ 'TRACK_OFFSET' }    = 20;
    $cookie->{ 'TRACK_SPACE' }     = 20;
    $cookie->{ 'RULER_FONT_SIZE' } = 10;     # Size of ruler font in pixels
    $cookie->{ 'RULER_COLOR' }     = [ 0, 0, 0 ];
    $cookie->{ 'SEQ_FONT_SIZE' }   = 10;
    $cookie->{ 'SEQ_COLOR' }       = [ 0, 0, 0, ];
    $cookie->{ 'FEAT_WIDTH' }      = 5;
    $cookie->{ 'FEAT_COLOR' }      = [ 0, 0, 0 ];
#    $cookie->{ 'FEAT_MAX' }        = 5000;   # TODO: Reduntant?

#    $cookie->{ 'LIST_USER' }       = Maasha::BGB::Track::list_users();  # TODO: Redundant?

    if ( $cookie->{ 'USER' } and not $cookie->{ 'LOGIN_ERROR' } )
    {
        $cookie->{ 'LIST_CLADE' }      = Maasha::BGB::Track::list_clades(     $cookie->{ 'USER' } );

        if ( $cookie->{ 'CLADE' } )
        {
            $cookie->{ 'LIST_GENOME' }     = Maasha::BGB::Track::list_genomes(    $cookie->{ 'USER' }, $cookie->{ 'CLADE' } );

            if ( $cookie->{ 'GENOME' } )
            {
                $cookie->{ 'LIST_ASSEMBLY' }   = Maasha::BGB::Track::list_assemblies( $cookie->{ 'USER' }, $cookie->{ 'CLADE' }, $cookie->{ 'GENOME' } );

                if ( $cookie->{ 'ASSEMBLY' } )
                {
                    $cookie->{ 'LIST_CONTIG' }     = Maasha::BGB::Track::list_contigs(    $cookie->{ 'USER' }, $cookie->{ 'CLADE' }, $cookie->{ 'GENOME' }, $cookie->{ 'ASSEMBLY' } );
                }
            }
        }

        if ( $cookie->{ 'CONTIG' } )
        {
            cookie_start( $cookie );
            cookie_end( $cookie );
            cookie_zoom( $cookie );
            cookie_move( $cookie );
            cookie_center( $cookie );
            cookie_track_status( $cookie );
        }
    }

    $cookie->{ 'STRAND' } = '+' if defined $cookie->{ 'STRAND' } and $cookie->{ 'STRAND' } eq ' ';   # FIXME ugly HTML fix

    session_store( $cookie, $session );

    return wantarray ? %{ $cookie } : $cookie;
}


sub session_restore
{
    # Martin A. Hansen, March 2010.

    # Restores session and returns this.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns hashref.

    my ( $session );

    if ( defined $cookie->{ 'USER' } and -d "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }" ) {
        $session = Maasha::BGB::Session::session_restore( "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }/session.json" );
    }

    return wantarray ? %{ $session } : $session;
}


sub session_store
{
    # Martin A. Hansen, March 2010.

    # Store a session updated with cookie information to session file.

    my ( $cookie,    # cookie hash
         $session,   # session hash
       ) = @_;

    # Returns nothing.

    my ( $new_session );

    if ( defined $cookie->{ 'USER' } and $cookie->{ 'USER' } ne '' and -d "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }" )
    {
        $new_session->{ 'PASSWORD' }   = $session->{ 'PASSWORD' };
        $new_session->{ 'SESSION_ID' } = $session->{ 'SESSION_ID' };
        $new_session->{ 'TIME' }       = Maasha::Common::time_stamp();
        $new_session->{ 'PAGE' }       = $cookie->{ 'PAGE' };

        if ( $cookie->{ 'PAGE' } =~ /browse|export_pdf|export_svg/ )
        {
            $new_session->{ 'CLADE' }     = $cookie->{ 'CLADE' };
            $new_session->{ 'GENOME' }    = $cookie->{ 'GENOME' };
            $new_session->{ 'ASSEMBLY' }  = $cookie->{ 'ASSEMBLY' };
            $new_session->{ 'CONTIG' }    = $cookie->{ 'CONTIG' };
            $new_session->{ 'NAV_START' } = $cookie->{ 'NAV_START' };
            $new_session->{ 'NAV_END' }   = $cookie->{ 'NAV_END' };
        }
        elsif ( $cookie->{ 'PAGE' } eq 'contig' )
        {
            $new_session->{ 'CLADE' }     = $cookie->{ 'CLADE' };
            $new_session->{ 'GENOME' }    = $cookie->{ 'GENOME' };
            $new_session->{ 'ASSEMBLY' }  = $cookie->{ 'ASSEMBLY' };
        }
        elsif ( $cookie->{ 'PAGE' } eq 'assembly' )
        {
            $new_session->{ 'CLADE' }     = $cookie->{ 'CLADE' };
            $new_session->{ 'GENOME' }    = $cookie->{ 'GENOME' };
        }
        elsif ( $cookie->{ 'PAGE' } eq 'genome' )
        {
            $new_session->{ 'CLADE' }     = $cookie->{ 'CLADE' };
        }
        elsif ( $cookie->{ 'PAGE' } =~ /export|dna/ )
        {
            $new_session->{ 'CLADE' }     = $cookie->{ 'CLADE' };
            $new_session->{ 'GENOME' }    = $cookie->{ 'GENOME' };
            $new_session->{ 'ASSEMBLY' }  = $cookie->{ 'ASSEMBLY' };
            $new_session->{ 'CONTIG' }    = $cookie->{ 'CONTIG' };
            $new_session->{ 'Q_ID' }      = $cookie->{ 'Q_ID' };
            $new_session->{ 'S_BEG' }     = $cookie->{ 'S_BEG' };
            $new_session->{ 'S_END' }     = $cookie->{ 'S_END' };
            $new_session->{ 'STRAND' }    = $cookie->{ 'STRAND' };
        }

        $new_session->{ 'TRACK_STATUS' } = $cookie->{ 'TRACK_STATUS' };

        Maasha::BGB::Session::session_store( "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }/session.json", $new_session );
    }
}


sub session_id_check
{
    # Martin A. Hansen, March 2010.

    # Check that the session id in the cookie and session match.
    # Sets SESSION_ERROR flag in cookie if not matching.

    my ( $cookie,    # cookie hash
         $session,   # session hash
       ) = @_;

    # Returns nothing.

    if ( defined $cookie->{ 'SESSION_ID' } and defined $session->{ 'SESSION_ID' } )
    {
        if ( $cookie->{ 'SESSION_ID' } ne $session->{ 'SESSION_ID' } ) {
            $cookie->{ 'SESSION_ERROR' } = 1;
        } else {
            $cookie->{ 'SESSION_ERROR' } = 0;
        }
    }
}


sub cookie_login
{
    # Martin A. Hansen, December 2009.

    # Check a user and password from CGI against the password file and
    # set the session ID, if found, in the cookie.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.

    my ( $session );

    if ( defined $cookie->{ 'PASSWORD' } )
    {
        if ( defined $cookie->{ 'USER' } and -d "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }" )
        {
            $session = Maasha::BGB::Session::session_restore( "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }/session.json" );

            if ( $session->{ 'PASSWORD' } eq Digest::MD5::md5_hex( $cookie->{ 'PASSWORD' } ) )
            {
                $cookie->{ 'TIME' }          = Maasha::Common::time_stamp();
                $cookie->{ 'SESSION_ID' }  ||= Maasha::BGB::Session::session_new();
                $cookie->{ 'LOGIN' }         = 1;
                $cookie->{ 'LOGIN_ERROR' }   = 0;
            }
            else
            {
                $cookie->{ 'LOGIN_ERROR' } = 1;
            }
        }
        else
        {
            $cookie->{ 'LOGIN_ERROR' } = 1;
        }
    }
}


sub cookie_start
{
    # Martin A. Hansen, November 2009.

    # Decommify the cookie value for NAV_START and adjust it to
    # to prevent negative values.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.

    if ( defined $cookie->{ 'NAV_START' } )
    {
        $cookie->{ 'NAV_START' } =~ tr/,//d;
        $cookie->{ 'NAV_START' } = 0 if $cookie->{ 'NAV_START' } < 0;
    }
    else
    {
        $cookie->{ 'NAV_START' } = 0;
    }
}


sub cookie_end
{
    # Martin A. Hansen, November 2009.

    # Decommify the cookie value for NAV_END and adjust it to prevent
    # overshooting the max value for the contig size as determined
    # from the cookie.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.

    my ( $max );
    
    $max = Maasha::Filesys::file_size( Maasha::BGB::Track::path_seq( $cookie ) );

    if ( defined $cookie->{ 'NAV_END' } )
    {
        $cookie->{ 'NAV_END' } =~ tr/,//d;
        $cookie->{ 'NAV_END' } = $max if $cookie->{ 'NAV_END' } > $max;
    }
    else
    {
        $cookie->{ 'NAV_END' } = $max;
    }
}


sub cookie_zoom
{
    # Martin A. Hansen, November 2009.

    # Adjust the cookie values for NAV_START and NAV_END based
    # on cookie ZOOM values.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.

    my ( $max, $dist, $new_dist, $dist_diff );

    $max = Maasha::Filesys::file_size( Maasha::BGB::Track::path_seq( $cookie ) );

    $dist = $cookie->{ 'NAV_END' } - $cookie->{ 'NAV_START' };

    if ( defined $cookie->{ 'ZOOM_IN1' } ) {
        $new_dist = $dist / 1.5;
    } elsif ( defined $cookie->{ 'ZOOM_IN2' } ) {
        $new_dist = $dist / 3;
    } elsif ( defined $cookie->{ 'ZOOM_IN3' } ) {
        $new_dist = $dist / 10;
    } elsif ( defined $cookie->{ 'ZOOM_OUT1' } ) {
        $new_dist = $dist * 1.5;
    } elsif ( defined $cookie->{ 'ZOOM_OUT2' } ) {
        $new_dist = $dist * 3;
    } elsif ( defined $cookie->{ 'ZOOM_OUT3' } ) {
        $new_dist = $dist * 10;
    }

    if ( $new_dist )
    {
        $dist_diff = $dist - $new_dist;

        $cookie->{ 'NAV_START' } = int( $cookie->{ 'NAV_START' } + ( $dist_diff / 2 ) );
        $cookie->{ 'NAV_END' }   = int( $cookie->{ 'NAV_END' }   - ( $dist_diff / 2 ) );

        $cookie->{ 'NAV_START' } = 0    if $cookie->{ 'NAV_START' } < 0;
        $cookie->{ 'NAV_END' }   = $max if $cookie->{ 'NAV_END' } > $max;
    }
}


sub cookie_move
{
    # Martin A. Hansen, November 2009.

    # Adjust the cookie values for NAV_START and NAV_END based
    # on cookie MOVE values.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.
    
    my ( $max, $dist, $shift, $new_start, $new_end );

    $max = Maasha::Filesys::file_size( Maasha::BGB::Track::path_seq( $cookie ) );

    $dist = $cookie->{ 'NAV_END' } - $cookie->{ 'NAV_START' };

    if ( defined $cookie->{ 'MOVE_LEFT1' } ) {
        $shift = -1 * $dist * 0.10;
    } elsif ( defined $cookie->{ 'MOVE_LEFT2' } ) {
        $shift = -1 * $dist * 0.475;
    } elsif ( defined $cookie->{ 'MOVE_LEFT3' } ) {
        $shift = -1 * $dist * 0.95;
    } elsif ( defined $cookie->{ 'MOVE_RIGHT1' } ) {
        $shift = $dist * 0.10;
    } elsif ( defined $cookie->{ 'MOVE_RIGHT2' } ) {
        $shift = $dist * 0.475;
    } elsif ( defined $cookie->{ 'MOVE_RIGHT3' } ) {
        $shift = $dist * 0.95;
    }

    if ( $shift )
    {
        $new_start = int( $cookie->{ 'NAV_START' } + $shift );
        $new_end   = int( $cookie->{ 'NAV_END' }   + $shift );

        if ( $new_start > 0 and $new_end < $max )
        {
            $cookie->{ 'NAV_START' } = $new_start;
            $cookie->{ 'NAV_END' }   = $new_end;
        }
    }
}


sub cookie_center
{
    # Martin A. Hansen, March 2010.
   
    # Adjust the cookie values for NAV_START and NAV_END based
    # on cookie CENTER value if defined.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.

    my ( $l_dist, $r_dist );

    if ( defined $cookie->{ 'NAV_CENTER' } )
    {
        $l_dist = $cookie->{ 'NAV_CENTER' } - $cookie->{ 'NAV_START' };
        $r_dist = $cookie->{ 'NAV_END' } - $cookie->{ 'NAV_CENTER' };

        if ( $l_dist > $r_dist ) {
            $cookie->{ 'NAV_START' } = $cookie->{ 'NAV_END' } - 2 * $r_dist;
        } else {
            $cookie->{ 'NAV_END' } = $cookie->{ 'NAV_START' } + 2 * $l_dist;
        }
    }
}


sub cookie_track_status
{
    # Martin A. Hansen, March 2010.

    #
    
    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns nothing.

    my ( $clade, $genome, $assembly, $track );

    $clade    = $cookie->{ 'CLADE' };
    $genome   = $cookie->{ 'GENOME' };
    $assembly = $cookie->{ 'ASSEMBLY' };
    $track    = $cookie->{ 'TRACK' };

    if ( $track )
    {
        if ( $cookie->{ 'TRACK_STATUS' }->{ $clade }->{ $genome }->{ $assembly }->{ $track } ) {
            $cookie->{ 'TRACK_STATUS' }->{ $clade }->{ $genome }->{ $assembly }->{ $track } = 0;
        } else {
            $cookie->{ 'TRACK_STATUS' }->{ $clade }->{ $genome }->{ $assembly }->{ $track } = 1;
        }
    }
}


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PAGES <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


sub page
{
    # Martin A. Hansen, November 2009.

    # Determines what page to render based on
    # the cookie's PAGE setting.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html );

    if ( $cookie->{ 'SESSION_ID' } ) {
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "session_id", value => $cookie->{ 'SESSION_ID' } ) );
    }

    if ( $cookie->{ 'PAGE' } eq 'login' ) {
        push @html, page_login( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'search' ) {
        push @html, page_search( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'browse' ) {
        push @html, page_browse( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'dna' ) {
        push @html, page_dna( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'export' ) {
        push @html, page_export( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'export_pdf' ) {
        push @html, page_export_pdf( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'export_svg' ) {
        push @html, page_export_svg( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'clade' ) {
        push @html, page_clade( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'genome' ) {
        push @html, page_genome( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'assembly' ) {
        push @html, page_assembly( $cookie );
    } elsif ( $cookie->{ 'PAGE' } eq 'contig' ) {
        push @html, page_contig( $cookie );
    }

    return wantarray ? @html : \@html;
}


sub page_login
{
    # Martin A. Hansen, December 2009.

    # Renders the login page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_login( $cookie );

    return wantarray ? @html : \@html;
}


sub page_search
{
    # Martin A. Hansen, December 2009.

    # Renders the search page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_search( $cookie );

    return wantarray ? @html : \@html;
}


sub page_browse
{
    # Martin A. Hansen, November 2009.
    
    # Renders the browse page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_navigate( $cookie );
    push @html, section_browse( $cookie );
    push @html, section_linkout( $cookie );

    return wantarray ? @html : \@html;
}


sub page_dna
{
    # Martin A. Hansen, November 2009.
    
    # Renders the DNA page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_dna( $cookie );

    return wantarray ? @html : \@html;
}


sub page_export
{
    # Martin A. Hansen, November 2009.

    # Renders the export page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_export( $cookie );

    return wantarray ? @html : \@html;
}


sub page_export_pdf
{
    # Martin A. Hansen, March 2010.

    # Renders the export PDF page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_export_pdf( $cookie );

    return wantarray ? @html : \@html;
}


sub page_export_svg
{
    # Martin A. Hansen, March 2010.

    # Renders the export SVG page.

    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_export_svg( $cookie );

    return wantarray ? @html : \@html;
}


sub page_clade
{
    # Martin A. Hansen, March 2010.
    
    # Renders the clade selection page.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_clade( $cookie );

    return wantarray ? @html : \@html;
}


sub page_genome
{
    # Martin A. Hansen, March 2010.
    
    # Renders the genome selection page.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_genome( $cookie );

    return wantarray ? @html : \@html;
}


sub page_assembly
{
    # Martin A. Hansen, March 2010.
    
    # Renders the clade selection page.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_assembly( $cookie );

    return wantarray ? @html : \@html;
}


sub page_contig
{
    # Martin A. Hansen, November 2009.
    
    # Renders the browse page.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html );

    push @html, section_taxonomy_table( $cookie );
    push @html, section_contig( $cookie );

    return wantarray ? @html : \@html;
}


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SECTIONS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


sub section_login
{
    # Martin A. Hansen, December 2009.
   
    # Returns a HTML section with a login menu.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( $user, $password, $login, @html );

    $user     = Maasha::XHTML::text( name => "user", value => "", size => 20 );
    $password = Maasha::XHTML::password( name => "password", value => "", size => 20 );
    $login    = Maasha::XHTML::submit( name => "login_submit", value => "Login" );

    push @html, Maasha::XHTML::h2( txt => "Login", class => 'center' );

    push @html, Maasha::XHTML::table_beg( summary => "Login table", align => 'center' );
    push @html, Maasha::XHTML::table_row_simple( tr => [ "User:", $user ] );
    push @html, Maasha::XHTML::table_row_simple( tr => [ "Password:", $password ] );
    push @html, Maasha::XHTML::table_row_simple( tr => [ "", $login ] );
    push @html, Maasha::XHTML::table_end;

    if ( defined $cookie->{ 'CLADE' }     and
         defined $cookie->{ 'GENOME' }    and
         defined $cookie->{ 'ASSEMBLY' }  and
         defined $cookie->{ 'CONTIG' }    and
         defined $cookie->{ 'NAV_START' } and
         defined $cookie->{ 'NAV_END' }
    )
    {
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "clade",     value => $cookie->{ 'CLADE' } ) );
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "genome",    value => $cookie->{ 'GENOME' } ) );
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "assembly",  value => $cookie->{ 'ASSEMBLY' } ) );
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "contig",    value => $cookie->{ 'CONTIG' } ) );
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "nav_start", value => $cookie->{ 'NAV_START' } ) );
        push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "nav_end",   value => $cookie->{ 'NAV_END' } ) );
    }

    if ( $cookie->{ 'LOGIN_ERROR' } ) {
        push @html, Maasha::XHTML::h3( txt => "Bad user or password - please retry", class => 'error' );
    }

    return wantarray ? @html : \@html;
}


sub section_taxonomy_table
{
    # Martin A. Hansen, November 2009.

    # Returns a HTML section with a taxonomy table
    # showing the location in the taxonomy and with
    # links to browse the taxonomy.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( $page, @row, @html, $href, $txt );
    
    foreach $page ( @{ $cookie->{ 'LIST_PAGES' } } )
    {
        last if $page eq $cookie->{ 'PAGE' } or $page eq 'browse';

        $href  = "$cookie->{ 'SCRIPT' }?page=$page";
        $href .= "&session_id=$cookie->{ 'SESSION_ID' }";
        $href .= "&user=$cookie->{ 'USER' }";
        $href .= "&clade=$cookie->{ 'CLADE' }"       if $page !~ /clade/;
        $href .= "&genome=$cookie->{ 'GENOME' }"     if $page !~ /clade|genome/;
        $href .= "&assembly=$cookie->{ 'ASSEMBLY' }" if $page !~ /clade|genome|assembly/;
        $href .= "&contig=$cookie->{ 'CONTIG' }"     if $page !~ /clade|genome|assembly|contig/;

        $txt = ": $cookie->{ uc $page }";

        push @row, Maasha::XHTML::ln( txt => $page, href => $href, class => 'inline' );
        push @row, Maasha::XHTML::p(  txt => $txt, class => 'inline' );
    }

    push @html, Maasha::XHTML::table_beg( summary => "Taxonomy table", align => 'center', cellpadding => '5px' );
    push @html, Maasha::XHTML::table_row_simple( tr => [ join( "\n", @row ) ], align => 'center' );
    push @html, Maasha::XHTML::table_end;

    return wantarray ? @html : \@html;
}


sub section_clade
{
    # Martin A. Hansen, March 2010.
    
    # Returns a HTML section with clade selection choices
    # for navigating the taxonomy tree.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html, $clade, $href );

    push @html, Maasha::XHTML::h2( txt => "Select clade", class => 'center' );

    push @html, Maasha::XHTML::table_beg( summary => "Taxonomy select table", align => 'center', cellpadding => '5px' );

    foreach $clade ( @{ $cookie->{ 'LIST_CLADE' } } )
    {
        $href  = "$cookie->{ 'SCRIPT' }?page=genome";
        $href .= "&session_id=$cookie->{ 'SESSION_ID' }";
        $href .= "&user=$cookie->{ 'USER' }";
        $href .= "&clade=$clade";

        push @html, Maasha::XHTML::table_row_simple( tr => [ Maasha::XHTML::ln( txt => $clade, href => $href ) ] );
    }

    push @html, Maasha::XHTML::table_end;

    return wantarray ? @html : \@html;
}


sub section_genome
{
    # Martin A. Hansen, March 2010.
    
    # Returns a HTML section with genome selection choices
    # for navigating the taxonomy tree.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html, $genome, $href );

    push @html, Maasha::XHTML::h2( txt => "Select genome", class => 'center' );

    push @html, Maasha::XHTML::table_beg( summary => "Taxonomy select table", align => 'center', cellpadding => '5px' );

    foreach $genome ( @{ $cookie->{ 'LIST_GENOME' } } )
    {
        $href  = "$cookie->{ 'SCRIPT' }?page=assembly";
        $href .= "&session_id=$cookie->{ 'SESSION_ID' }";
        $href .= "&user=$cookie->{ 'USER' }";
        $href .= "&clade=$cookie->{ 'CLADE' }";
        $href .= "&genome=$genome";

        push @html, Maasha::XHTML::table_row_simple( tr => [ Maasha::XHTML::ln( txt => $genome, href => $href ) ] );
    }

    push @html, Maasha::XHTML::table_end;

    return wantarray ? @html : \@html;
}


sub section_assembly
{
    # Martin A. Hansen, March 2010.
    
    # Returns a HTML section with assembly selection choices
    # for navigating the taxonomy tree.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html, $assembly, $href );

    push @html, Maasha::XHTML::h2( txt => "Select assembly", class => 'center' );

    push @html, Maasha::XHTML::table_beg( summary => "Taxonomy select table", align => 'center', cellpadding => '5px' );

    foreach $assembly ( @{ $cookie->{ 'LIST_ASSEMBLY' } } )
    {
        $href  = "$cookie->{ 'SCRIPT' }?page=contig";
        $href .= "&session_id=$cookie->{ 'SESSION_ID' }";
        $href .= "&user=$cookie->{ 'USER' }";
        $href .= "&clade=$cookie->{ 'CLADE' }";
        $href .= "&genome=$cookie->{ 'GENOME' }";
        $href .= "&assembly=$assembly";

        push @html, Maasha::XHTML::table_row_simple( tr => [ Maasha::XHTML::ln( txt => $assembly, href => $href ) ] );
    }

    push @html, Maasha::XHTML::table_end;

    return wantarray ? @html : \@html;
}


sub section_contig
{
    # Martin A. Hansen, March 2010.
    
    # Returns a HTML section with contig selection choices
    # for navigating the taxonomy tree.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html, $contig, $href );

    push @html, Maasha::XHTML::h2( txt => "Select contig", class => 'center' );

    push @html, Maasha::XHTML::table_beg( summary => "Taxonomy select table", align => 'center', cellpadding => '5px' );

    foreach $contig ( @{ $cookie->{ 'LIST_CONTIG' } } )
    {
        $href  = "$cookie->{ 'SCRIPT' }?page=browse";
        $href .= "&session_id=$cookie->{ 'SESSION_ID' }";
        $href .= "&user=$cookie->{ 'USER' }";
        $href .= "&clade=$cookie->{ 'CLADE' }";
        $href .= "&genome=$cookie->{ 'GENOME' }";
        $href .= "&assembly=$cookie->{ 'ASSEMBLY' }";
        $href .= "&contig=$contig";

        push @html, Maasha::XHTML::table_row_simple( tr => [ Maasha::XHTML::ln( txt => $contig, href => $href ) ] );
    }

    push @html, Maasha::XHTML::table_end;

    return wantarray ? @html : \@html;
}


sub section_navigate
{
    # Martin A. Hansen, November 2009.

    # Returns a HTML section for navigating in the browser window.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html, $nav_val );

    $nav_val = Maasha::Calc::commify( $cookie->{ 'NAV_START' } ) . "-" . Maasha::Calc::commify( $cookie->{ 'NAV_END' } );

    push @html, Maasha::XHTML::table_beg( summary => "Navigation table", align => 'center' );
    push @html, Maasha::XHTML::table_row_simple( tr => [
        "Position or search term:",
        Maasha::XHTML::text( name => "nav_search", value => $nav_val, size => 30 ),
        Maasha::XHTML::submit( name => "nav_submit", value => "Submit" ),
    ] );
    push @html, Maasha::XHTML::table_end;

    push @html, Maasha::XHTML::table_beg( summary => "Zoom table", align => 'center' );
    push @html, Maasha::XHTML::table_row_simple( tr => [
        Maasha::XHTML::p( txt => 'Move:' ),
        Maasha::XHTML::submit( name => "move_left3",  value => "<<<", title => "move 95% to the left" ),
        Maasha::XHTML::submit( name => "move_left2",  value => "<<",  title => "move 47.5% to the left" ),
        Maasha::XHTML::submit( name => "move_left1",  value => "<",   title => "move 10% to the left" ),
        Maasha::XHTML::submit( name => "move_right1", value => ">",   title => "move 10% to the rigth" ),
        Maasha::XHTML::submit( name => "move_right2", value => ">>",  title => "move 47.5% to the rigth" ),
        Maasha::XHTML::submit( name => "move_right3", value => ">>>", title => "move 95% to the right" ),
        Maasha::XHTML::p( txt => 'Zoom in:' ),
        Maasha::XHTML::submit( name => "zoom_in1", value => "1.5x" ),
        Maasha::XHTML::submit( name => "zoom_in2", value => "3x" ),
        Maasha::XHTML::submit( name => "zoom_in3", value => "10x" ),
        Maasha::XHTML::p( txt => 'Zoom out:' ),
        Maasha::XHTML::submit( name => "zoom_out1", value => "1.5x" ),
        Maasha::XHTML::submit( name => "zoom_out2", value => "3x" ),
        Maasha::XHTML::submit( name => "zoom_out3", value => "10x" ),
    ] );
    push @html, Maasha::XHTML::table_end;

    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "page",     value => "browse" ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "user",     value => $cookie->{ 'USER' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "clade",    value => $cookie->{ 'CLADE' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "genome",   value => $cookie->{ 'GENOME' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "assembly", value => $cookie->{ 'ASSEMBLY' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "contig",   value => $cookie->{ 'CONTIG' } ) );

    return wantarray ? @html : \@html;
}


sub section_linkout
{
    # Martin A. Hansen, March 2010.

    # Returns a HTML section for a static link based on information in the cookie.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( $link_out, $link_pdf, $link_svg, @html );

    $link_out = Maasha::XHTML::ln(
        txt  => 'link',
        href => join( "&", "$cookie->{ 'SCRIPT' }?page=browse",
                           "clade=$cookie->{ 'CLADE' }",
                           "genome=$cookie->{ 'GENOME' }",
                           "assembly=$cookie->{ 'ASSEMBLY' }",
                           "contig=$cookie->{ 'CONTIG' }",
                           "nav_start=$cookie->{ 'NAV_START' }",
                           "nav_end=$cookie->{ 'NAV_END' }",
              ),
        title  => "Static link to this view",
    );

    $link_pdf = Maasha::XHTML::ln(
        txt  => 'PDF',
        href => join( "&", "$cookie->{ 'SCRIPT' }?page=export_pdf",
                           "session_id=$cookie->{ 'SESSION_ID' }",
                           "user=$cookie->{ 'USER' }",
                           "clade=$cookie->{ 'CLADE' }",
                           "genome=$cookie->{ 'GENOME' }",
                           "assembly=$cookie->{ 'ASSEMBLY' }",
                           "contig=$cookie->{ 'CONTIG' }",
                           "nav_start=$cookie->{ 'NAV_START' }",
                           "nav_end=$cookie->{ 'NAV_END' }",
              ),
        title  => "Export view in PDF",
    );
    
    $link_svg = Maasha::XHTML::ln(
        txt  => 'SVG',
        href => join( "&", "$cookie->{ 'SCRIPT' }?page=export_svg",
                           "session_id=$cookie->{ 'SESSION_ID' }",
                           "user=$cookie->{ 'USER' }",
                           "clade=$cookie->{ 'CLADE' }",
                           "genome=$cookie->{ 'GENOME' }",
                           "assembly=$cookie->{ 'ASSEMBLY' }",
                           "contig=$cookie->{ 'CONTIG' }",
                           "nav_start=$cookie->{ 'NAV_START' }",
                           "nav_end=$cookie->{ 'NAV_END' }",
              ),
        title  => "Export view in SVG",
    );

    push @html, Maasha::XHTML::p( txt => "$link_out $link_pdf $link_svg", class => 'center' );

    return wantarray ? @html : \@html;
}


sub section_browse
{
    my ( $cookie,
       ) = @_;

    # Returns a list.

    my ( @track_list, $i, @tracks, $track, $elem, $png_data, @html, @img, $x1, $y1, $x2, $y2, $factor, $center );

    push @tracks, [ Maasha::BGB::Track::track_ruler( $cookie ) ];
    push @tracks, [ Maasha::BGB::Track::track_seq( $cookie ) ];

    @track_list = Maasha::BGB::Track::list_track_dir( $cookie->{ 'USER' }, $cookie->{ 'CLADE' }, $cookie->{ 'GENOME' }, $cookie->{ 'ASSEMBLY' }, $cookie->{ 'CONTIG' } );

    for ( $i = 0; $i < @track_list; $i++ )
    {
        $cookie->{ 'FEAT_COLOR' } = Maasha::BGB::Draw::palette( $i );

        push @tracks, [ Maasha::BGB::Track::track_feature( $track_list[ $i ], $cookie ) ];
    }

    unshift @tracks, [ Maasha::BGB::Track::track_grid( $cookie ) ];

    $png_data = Maasha::BGB::Draw::render_png( $cookie->{ 'IMG_WIDTH' }, $cookie->{ 'TRACK_OFFSET' }, \@tracks );

    push @img, Maasha::XHTML::img(
        src    => "data:image/png;base64,$png_data",
        alt    => "Browser Tracks",
        height => $cookie->{ 'TRACK_OFFSET' },
        width  => $cookie->{ 'IMG_WIDTH' },
        id     => "browser_map",
        usemap => "#browser_map"
    );

    push @img, Maasha::XHTML::map_beg( name => "browser_map", id => "browser_map" );

    $factor = ( $cookie->{ 'NAV_END' } - $cookie->{ 'NAV_START' } + 1 ) / $cookie->{ 'IMG_WIDTH' };

    for ( $i = 0; $i < $cookie->{ 'IMG_WIDTH' }; $i += 5 )
    {
        $x1 = $i;
        $y1 = 10;
        $x2 = $i + 5;
        $y2 = 20;

        $center = int( $cookie->{ 'NAV_START' } + $factor * $i );

        push @img, Maasha::XHTML::area(
            href   => join( "&", "$cookie->{ 'SCRIPT' }?page=browse",
                                 "session_id=$cookie->{ 'SESSION_ID' }",
                                 "user=$cookie->{ 'USER' }",
                                 "clade=$cookie->{ 'CLADE' }",
                                 "genome=$cookie->{ 'GENOME' }",
                                 "assembly=$cookie->{ 'ASSEMBLY' }",
                                 "contig=$cookie->{ 'CONTIG' }",
                                 "nav_start=$cookie->{ 'NAV_START' }",
                                 "nav_end=$cookie->{ 'NAV_END' }",
                                 "nav_center=$center",
                      ),
            shape  => 'rect',
            coords => "$x1, $y1, $x2, $y2",
            title  => "Center on " . Maasha::Calc::commify( $center ),
        );
    }

    foreach $track ( @tracks )
    {
        foreach $elem ( @{ $track } )
        {
            next if $elem->{ 'type' } =~ /grid|text|wiggle/;

            if ( $elem->{ 'type' } eq 'track_name' )
            {
                $x1 = $elem->{ 'x1' };
                $y1 = $elem->{ 'y1' } - 10;
                $x2 = $elem->{ 'x1' } + 6 * length $elem->{ 'txt' };
                $y2 = $elem->{ 'y1' };

                if ( Maasha::BGB::Track::track_hide( $cookie, $elem->{ 'track' } ) )
                {
                    push @img, Maasha::XHTML::area(
                        href   => join( "&", "$cookie->{ 'SCRIPT' }?page=browse",
                                             "session_id=$cookie->{ 'SESSION_ID' }",
                                             "user=$cookie->{ 'USER' }",
                                             "clade=$cookie->{ 'CLADE' }",
                                             "genome=$cookie->{ 'GENOME' }",
                                             "assembly=$cookie->{ 'ASSEMBLY' }",
                                             "contig=$cookie->{ 'CONTIG' }",
                                             "track=$elem->{ 'track' }",
                                  ),
                        shape  => 'rect',
                        coords => "$x1, $y1, $x2, $y2",
                        title  => qq(Show track: $elem->{ 'txt' }),
                    );
                }
                else
                {
                    push @img, Maasha::XHTML::area(
                        href   => join( "&", "$cookie->{ 'SCRIPT' }?page=browse",
                                             "session_id=$cookie->{ 'SESSION_ID' }",
                                             "user=$cookie->{ 'USER' }",
                                             "clade=$cookie->{ 'CLADE' }",
                                             "genome=$cookie->{ 'GENOME' }",
                                             "assembly=$cookie->{ 'ASSEMBLY' }",
                                             "contig=$cookie->{ 'CONTIG' }",
                                             "track=$elem->{ 'track' }",
                                  ),
                        shape  => 'rect',
                        coords => "$x1, $y1, $x2, $y2",
                        title  => qq(Hide track: $elem->{ 'txt' }),
                    );
                }
            }
            else
            {
                push @img, Maasha::XHTML::area(
                    href     => join( "&", "$cookie->{ 'SCRIPT' }?page=export",
                                           "session_id=$cookie->{ 'SESSION_ID' }",
                                           "user=$cookie->{ 'USER' }",
                                           "clade=$cookie->{ 'CLADE' }",
                                           "genome=$cookie->{ 'GENOME' }",
                                           "assembly=$cookie->{ 'ASSEMBLY' }",
                                           "contig=$cookie->{ 'CONTIG' }",
                                           "s_beg=$elem->{ 's_beg' }",
                                           "s_end=$elem->{ 's_end' }",
                                           "strand=$elem->{ 'strand' }",
                                           "q_id=$elem->{ 'q_id' }",
                              ),
                    shape  => 'rect',
                    coords => "$elem->{ x1 }, $elem->{ y1 }, $elem->{ x2 }, $elem->{ y2 }",
                    title  => "$elem->{ 'title' }",
                );
            }
        }
    }

    push @img, Maasha::XHTML::map_end();

    push @html, Maasha::XHTML::p( txt => join( "\n", @img ) );

    @html = Maasha::XHTML::div( txt => join( "\n", @html ), class => 'browse' );

    return wantarray ? @html : \@html;
}


sub section_export
{
    # Martin A. Hansen, November 2009.

    # Returns a HTML section with export table.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( $feat, @row_dna_contig, @html );

    $feat = $cookie->{ 'Q_ID' } || "[no name]";

    push @row_dna_contig, Maasha::XHTML::p( txt => qq(Export Feature: "$feat" DNA from Contig: ), class => 'inline' );
    push @row_dna_contig, Maasha::XHTML::p( txt  => "$cookie->{ 'CONTIG' } Start: ", class => 'inline' );
    push @row_dna_contig, Maasha::XHTML::text( name => "s_beg", value => Maasha::Calc::commify( $cookie->{ 'S_BEG' } ), size => 15 );
    push @row_dna_contig, Maasha::XHTML::p( txt => "End: ", class => 'inline' );
    push @row_dna_contig, Maasha::XHTML::text( name => "s_end", value => Maasha::Calc::commify( $cookie->{ 'S_END' } ), size => 15 );
    push @row_dna_contig, Maasha::XHTML::p( txt => "Strand: ", class => 'inline' );
    push @row_dna_contig, Maasha::XHTML::menu( name => "strand", options => [ qw( + - ) ], selected => $cookie->{ 'STRAND' } );
    push @row_dna_contig, Maasha::XHTML::submit( name => "export", value => "Export", title => "Fetch DNA from this region" );

    push @html, Maasha::XHTML::h2( txt => "Export", class => 'center' );
    push @html, Maasha::XHTML::table_beg( summary => "Taxonomy select table", align => 'center' );
    push @html, Maasha::XHTML::table_row_simple( tr => \@row_dna_contig );
    push @html, Maasha::XHTML::table_end;

    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "page",     value => "dna" ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "user",     value => $cookie->{ 'USER' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "clade",    value => $cookie->{ 'CLADE' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "genome",   value => $cookie->{ 'GENOME' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "assembly", value => $cookie->{ 'ASSEMBLY' } ) );
    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::hidden( name => "contig",   value => $cookie->{ 'CONTIG' } ) );

    return wantarray ? @html : \@html;
}


sub section_export_pdf
{
    # Martin A. Hansen, March 2010.

    # Returns a HTML section with export table.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @tracks, @track_list, $i, $file, @html );

    push @tracks, [ Maasha::BGB::Track::track_ruler( $cookie ) ];
    push @tracks, [ Maasha::BGB::Track::track_seq( $cookie ) ];

    @track_list = Maasha::BGB::Track::list_track_dir( $cookie->{ 'USER' }, $cookie->{ 'CLADE' }, $cookie->{ 'GENOME' }, $cookie->{ 'ASSEMBLY' }, $cookie->{ 'CONTIG' } );

    for ( $i = 0; $i < @track_list; $i++ )
    {
        $cookie->{ 'FEAT_COLOR' } = Maasha::BGB::Draw::palette( $i );

        push @tracks, [ Maasha::BGB::Track::track_feature( $track_list[ $i ], $cookie ) ];
    }

    unshift @tracks, [ Maasha::BGB::Track::track_grid( $cookie ) ];

    $file = "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }/BGB_export.pdf";

    Maasha::BGB::Draw::render_pdf_file( $file, $cookie->{ 'IMG_WIDTH' }, $cookie->{ 'TRACK_OFFSET' }, \@tracks );

    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::ln( txt => "BGB_export.pdf", href => $file ), class => 'center' );

    return wantarray ? @html : \@html;
}


sub section_export_svg
{
    # Martin A. Hansen, March 2010.

    # Export view in SVG format.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @tracks, @track_list, $i, $file, @html );

    push @tracks, [ Maasha::BGB::Track::track_ruler( $cookie ) ];
    push @tracks, [ Maasha::BGB::Track::track_seq( $cookie ) ];

    @track_list = Maasha::BGB::Track::list_track_dir( $cookie->{ 'USER' }, $cookie->{ 'CLADE' }, $cookie->{ 'GENOME' }, $cookie->{ 'ASSEMBLY' }, $cookie->{ 'CONTIG' } );

    for ( $i = 0; $i < @track_list; $i++ )
    {
        $cookie->{ 'FEAT_COLOR' } = Maasha::BGB::Draw::palette( $i );

        push @tracks, [ Maasha::BGB::Track::track_feature( $track_list[ $i ], $cookie ) ];
    }

    unshift @tracks, [ Maasha::BGB::Track::track_grid( $cookie ) ];

    $file = "$cookie->{ 'SESSION_DIR' }/$cookie->{ 'USER' }/BGB_export.svg";

    Maasha::BGB::Draw::render_svg_file( $file, $cookie->{ 'IMG_WIDTH' }, $cookie->{ 'TRACK_OFFSET' }, \@tracks );

    push @html, Maasha::XHTML::p( txt => Maasha::XHTML::ln( txt => "BGB_export.svg", href => $file ), class => 'center' );

    return wantarray ? @html : \@html;
}


sub section_search
{
    # Martin A. Hansen, November 2009.

    # Returns a HTML section with export table.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( $results, $result, $count, @html, $export, $browse );

    $results = Maasha::BGB::Track::search_tracks( $cookie );

    $count = scalar @{ $results };

    push @html, Maasha::XHTML::h2( txt => "Search", class => 'center' );
    push @html, Maasha::XHTML::p( txt => qq(Results for "$cookie->{ 'SEARCH' }": $count), class => 'center' );

    if ( $count > 0 )
    {
        push @html, Maasha::XHTML::table_beg( summary => "Search table", align => 'center', cellpadding => '5px' );
        push @html, Maasha::XHTML::table_row_simple( tr => [ qw( S_ID S_BEG S_END Q_ID SCORE STRAND HITS ALIGN BLOCK_COUNT BLOCK_BEGS BLOCK_LENS BLOCK_TYPE) ] );

        foreach $result ( @{ $results } )
        {
            $cookie->{ 'CONTIG' }    = $result->{ 'S_ID' };
            $cookie->{ 'NAV_START' } = $result->{ 'S_BEG' };
            $cookie->{ 'NAV_END' }   = $result->{ 'S_END' };
            $cookie->{ 'S_BEG' }     = $result->{ 'S_BEG' };
            $cookie->{ 'S_END' }     = $result->{ 'S_END' };
            $cookie->{ 'STRAND' }    = $result->{ 'STRAND' };
            $cookie->{ 'Q_ID' }      = $result->{ 'Q_ID' };

            $browse = Maasha::XHTML::ln(
                txt  => "browse",
                href => join( "&", "$cookie->{ 'SCRIPT' }?page=browse",
                                   "session_id=$cookie->{ 'SESSION_ID' }",
                                   "user=$cookie->{ 'USER' }",
                                   "clade=$cookie->{ 'CLADE' }",
                                   "genome=$cookie->{ 'GENOME' }",
                                   "assembly=$cookie->{ 'ASSEMBLY' }",
                                   "contig=$cookie->{ 'CONTIG' }",
                                   "nav_start=$cookie->{ 'NAV_START' }",
                                   "nav_end=$cookie->{ 'NAV_END' }",
                ),
            );


            $export = Maasha::XHTML::ln(
                txt  => "export",
                href => join( "&", "$cookie->{ 'SCRIPT' }?page=export",
                                   "session_id=$cookie->{ 'SESSION_ID' }",
                                   "user=$cookie->{ 'USER' }",
                                   "clade=$cookie->{ 'CLADE' }",
                                   "genome=$cookie->{ 'GENOME' }",
                                   "assembly=$cookie->{ 'ASSEMBLY' }",
                                   "contig=$cookie->{ 'CONTIG' }",
                                   "s_beg=$cookie->{ 'S_BEG' }",
                                   "s_end=$cookie->{ 'S_END' }",
                                   "strand=$cookie->{ 'STRAND' }",
                ),
            );

            push @html, Maasha::XHTML::table_row_advanced(
                tr => [ { td => $result->{ 'S_ID' } },
                        { td => $result->{ 'S_BEG' }, align => 'right' },
                        { td => $result->{ 'S_END' }, align => 'right' },
                        { td => $result->{ 'Q_ID' } },
                        { td => $result->{ 'SCORE' }, align => 'right' },
                        { td => $result->{ 'STRAND' } },
                        { td => $result->{ 'HITS' }, align => 'right' },
                        { td => $result->{ 'ALIGN' } },
                        { td => $result->{ 'BLOCK_COUNT' }, align => 'right' },
                        { td => $result->{ 'BLOCK_BEGS' } },
                        { td => $result->{ 'BLOCK_LENS' } },
                        { td => $result->{ 'BLOCK_TYPE' } },
                        { td => $browse },
                        { td => $export },
                ], class => "monospace"
            );
        }

        push @html, Maasha::XHTML::table_end;
    }

    return wantarray ? @html : \@html;
}


sub section_dna
{
    # Martin A. Hansen, November 2009.

    # Returns a HTML section with extracted DNA.

    my ( $cookie,   # cookie hash
       ) = @_;

    # Returns a list.

    my ( @html, $beg, $end, $seq );
    
    $beg = $cookie->{ 'S_BEG' };
    $end = $cookie->{ 'S_END' };
    $beg =~ tr/,//d;
    $end =~ tr/,//d;

    $seq = join ";", ">$cookie->{ 'GENOME' }", $cookie->{ 'ASSEMBLY' }, $cookie->{ 'CONTIG' }, $beg, $end, "$cookie->{ 'STRAND' }\n";
    $seq .= Maasha::BGB::Track::dna_get( $cookie );

    push @html, Maasha::XHTML::h2( txt => "DNA", class => 'center' );
    push @html, Maasha::XHTML::pre( txt => $seq );

    return wantarray ? @html : \@html;
}


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


__END__


    # my $t0 = Time::HiRes::gettimeofday();
    # my $t1 = Time::HiRes::gettimeofday(); print STDERR "Time: " . ( $t1 - $t0 ) . "\n";
